<?php

class Security
{
	var $connDB = 1;
	var $func = 1;
	var $sqlFunc = 1;
	var $firstMake = 0;
	var $request = 1;
	var $error = 1;
	var $session = 1;
	var $appLog = 1;
	var $socket = 1;

	function makeSession()
	{
		$char[0] = "B";
		$char[1] = "C";
		$char[2] = "D";
		$char[3] = "F";
		$char[4] = "G";
		$char[5] = "H";
		$char[6] = "L";
		$char[7] = "M";
		$char[8] = "N";
		$char[9] = "P";
		
		session_start();
		session_regenerate_id( false );
		$sessId = session_id();
		$value = '';
		$valueTmp = rand(0,99999999);
		$tot = strlen($valueTmp);
		while( $tot-- )
		{
			$value.= $char[ intval(substr($valueTmp, $tot, 1)) ];
		}
		setcookie(COOKIE.$value, $sessId, time() + TIMESESSION);
//		print COOKIE.$value."<br>";
//		setcookie(COOKIE.$value, $sessId, 0);
		$this->firstMake = true;
 		return COOKIE.$value;
	}

	function startSession()
	{
		session_id( $_COOKIE[ $this->request["sessid"] ] );
		setcookie($this->request["sessid"], $_COOKIE[ $this->request["sessid"] ], time() + TIMESESSION);
		session_start();
	}

	function insSession()
	{
		$this->sqlFunc->init();
	}
	
	function updSession()
	{
		$this->sqlFunc->init();
	}
	
	function checkModule($gruppo, $mod, $do)
	{
		if ( $gruppo == "" || $mod == "" || $do == "")
		{
			$this->error = "Sessione scaduta";
			return true;
		}
		else
		{
			$sql = "SELECT 'x' ";
			$sql.= "  FROM um_moduli_gruppi mgr, ";
			$sql.= "	   um_moduli mod ";
			$sql.= " WHERE mgr.um_gruppo_id = $gruppo";
			$sql.= "   AND mod.um_modulo_id = mgr.um_modulo_id ";
			$sql.= "   AND mod.um_mod = '$mod' ";
			$sql.= "   AND mod.um_do = '$do' ";
	
			$this->appLog->logWrite($sql, 9);
			
			$rs = $this->connDB->Execute($sql);
			if ( ! $rs ) 
			{
				$this->appLog->logWrite("Error checkModule: ".$this->connDB->ErrorMsg(), 0);
				//print 'Error checkModule: '.$this->connDB->ErrorMsg().'<BR>';
				exit;
			}
	
			if ( $rs->RecordCount() > 0 ) return 0;
	
			$this->error = "Utente non abilitato ad accedere a questo modulo";
			return true;
		}
		return false;
	}

	function checkAuthDB( $username, $password, &$idUtente, &$gruppo ,&$nominativo ,&$idAnagrafica, &$voip, &$operatore)
	{
		$this->connDB->SetFetchMode(ADODB_FETCH_NUM);
        // $this->connDB->SetFetchMode(ADODB_FETCH_ASSOC);
		$this->error = '';
		if ( $username != '' )
		{
			//print "ok";
			//$password = md5($password);
			$sql = "SELECT ute.id_utente, ruolo, nome, cognome, id_anagrafica, voip , operatore
				FROM contaq_utenti AS ute
				LEFT JOIN contaq_anagrafica_utenti AS ana ON (ute.id_utente = ana.id_utente)
				WHERE username = '$username'
				AND password = '$password'
				AND attivo = 1";
			
// 			print "$sql";
			$this->appLog->logWrite($sql, 9);
			$rs = $this->connDB->Execute($sql);
			if ( ! $rs ) {
				print 'Error checkAuth: '.$this->connDB->ErrorMsg().'<BR>';
				exit;
			}
			
			if ($rs->RecordCount() > 0)
			{
				while ($arr = $rs->FetchRow())
				{
					//print_r ($arr);
					$idUtente = $arr[0];
					$gruppo = $arr[1];
					$nominativo = $arr[2].' '.$arr[3];
					$idAnagrafica = $arr[4];
					$voip = $arr[5];
					$operatore = $arr[6];
					return '';
				}
			}
			else
			{
				$this->error = "Utente e/o Password errati.";
				$idUtente = -1;
				$gruppo = -1;
				$idAnagrafica = -1;
			}
		}
		elseif ( isset($this->request['first']) )
		{
			$this->error = "Inserire l'Utente.";
			$idUtente = -1;
			$gruppo = -1;
			$idAnagrafica = -1;
		}
		else
		{
			$idUtente = -1;
			$gruppo = -1;
			$idAnagrafica = -1;
		}
		return '';
	}

	function checkSessionDB($sessid)
	{
		$this->startSession( $sessid );
		return 0;
		
		$this->connDB->SetFetchMode(ADODB_FETCH_NUM);
        // $this->connDB->SetFetchMode(ADODB_FETCH_ASSOC);
		
		$sql = "SELECT um.um_uid, grp.um_name, um.um_utente_id
					FROM um_users um
						, um_assign ass
						, um_groups as grp
					WHERE um.um_flag = '".DBINS."'
					AND um.um_username = '$username'
					AND um.um_password = '$password'
					AND ass.um_uid = um.um_uid
					AND grp.um_gid = ass.um_gid";
		
		$this->appLog->logWrite($sql, 9);
		$rs = $this->connDB->Execute($sql);
		if ( ! $rs ) {
			print 'Error checkAuth: '.$this->connDB->ErrorMsg().'<BR>';
			exit;
		}
		
		$chk = 1;
		while ( $arr = $rs->FetchRow() )
		{
			$chk = 0;
		}
		return $chk;
	}

/* SERVER SOCKET */
	function checkSession($sessid)
	{
		$control = $this->socket->reqRemoteResponse( "LOGIN $sessid" );
		
		$this->appLog->logWrite("checkSession: $control");
		if ( preg_match("/^OK/",$control) )
		{
			$this->startSession( $sessid );
			return false;
		}
		else
		{
			return true;
		}
	}

	function closeSessionDB($sessid)
	{
		session_destroy();
		$this->appLog->logWrite('closeSession');
	}
	
	function closeSession($sessid)
	{
		$this->socket->txData( "LOGOUT $sessid\n" );
		session_destroy();
		$this->appLog->logWrite('closeSession');
	}

	function checkAzienda( $azienda )
	{
		$control = $this->socket->reqRemoteResponse( "LOGIN_REGISTER $azienda|php" );
		
		$this->appLog->logWrite("checkAuth: $user = $control");

		if ( preg_match("/^OK/",$control) )
		{
			return 1;
		}
		else
		{
			$this->error = "Azienda non esiste";
			return 0;
		}
	}

	function checkAuth($user, $pass, &$idUtente, &$azienda, &$ruolo, &$idAnagrafica, &$visione, &$sessid)
	{
		if ( $user != "" )
		{
			$control = $this->socket->reqRemoteResponse( "LOGIN $azienda|php|$user|$pass" );
			
			$this->appLog->logWrite("checkAuth: $user = $control");

			if ( preg_match("/^OK/",$control) )
			{
				$control = preg_replace("/\n$/", "",$control);
				$control = str_replace("OK ","", $control);
				$tmp = split("\|", $control);
				$idUtente = $tmp[0];
				$azienda = $tmp[1];
				$ruolo = $tmp[2];
				$idAnagrafica = $tmp[3];
				$visione = $tmp[4];
				$sessid = $tmp[5];
			}
			else
			{
				$this->error = "Utente e/o Password errati.";
				return -1;
			}
		}
		else
		{
			return -1;
		}
	}

}

?>